# -*- coding:utf-8 -*-

# @Time    : 2023/12/13 07:05
# @Author  : yaodong
# @Email   : yaodong@lingxi.ai
# @File    : QWContactCallBackProcess.py
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# 用于处理企微渠道联系人相关的服务
import asyncio
import json
import traceback
import uuid
from datetime import datetime

import aiohttp

from bot.insurance_planner_gpt.qw_server.access_token_manager import token_manager
from bot.insurance_planner_gpt.qw_server.common import wework_constants
from db.mysql.entity_service import EntitiesDao
from db.redis.redis_service import RedisMemory

from common.log import logger
from bot.insurance_planner_gpt.qw_server.utils import common_util
from bot.insurance_planner_gpt.qw_server.utils import wechat

# from bot.insurance_planner_gpt.qw_server.qw_process import qw_process_msg

redis_memory = RedisMemory()
loops = asyncio.get_event_loop()
entities_dao = EntitiesDao()


class QWContactCallBackProcess:

    def __init__(self, company_id, event_type, robot_id, req_id, message) -> None:
        self.event_type = event_type
        self.robot_id = robot_id
        self.company_id = company_id
        self.req_id = req_id
        self.data = message.get("data", {})

    async def process_all_event_type(self):
        if wework_constants.WEWORK_EVENT_TYPE_BECOME_CONTACT == self.event_type:
            await self.become_contact()
        elif wework_constants.WEWORK_EVENT_TYPE_CONTACT_APPLY_REQ == self.event_type:
            logger.info("小助收到一个新的用户添加请求")
        elif wework_constants.WEWORK_EVENT_TYPE_GET_CONTACT == self.event_type:
            logger.info("获取用户详情")
        elif wework_constants.WEWORK_EVENT_TYPE_ADD_CONTACT_BY_PHONE == self.event_type:
            await self.process_add_by_phone()
        elif wework_constants.WEWORK_EVENT_TYPE_UPDATE_CONTACT_REMARK == self.event_type:
            await self.process_update_contact_remark()

    async def become_contact(self):
        contact_id = self.data.get('contact_id', '')
        contact_name = self.data.get('contact_name', '')
        avatar = self.data.get('avatar', '')
        add_way = self.data.get('add_way', '')
        mark_id_list = self.data.get('mark_id_list', '')
        dm_session_id = ""
        customer_id = ''
        if mark_id_list:
            dm_session_id = mark_id_list[0]
            idArr = str(dm_session_id).split(',')
            if len(idArr) > 1:
                dm_session_id = idArr[0]
                customer_id = idArr[1]

        user_type = self.data.get('user_type', '')
        session_id = self.robot_id + ":" + contact_id
        logger.info(f"当前会话:[{session_id}],外呼id:[{mark_id_list}],小助成功加上好友,开始处理...")
        if user_type and wework_constants.WEWORK_USER_TYPE_WEWORK_CONTACT == user_type:
            # 顾问缓存
            redis_memory.set(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "agent:" + contact_id,
                             json.dumps({"contact_id": contact_id, "name": contact_name, "avatar": avatar},
                                        ensure_ascii=False))
        elif user_type and wework_constants.WEWORK_USER_TYPE_WECHAT_CONTACT == user_type:
            # 用户缓存
            redis_memory.set(
                wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "user:" + str(self.company_id) + ":" + contact_id,
                json.dumps({"contact_id": contact_id, "name": contact_name, "avatar": avatar},
                           ensure_ascii=False))
            loops.run_in_executor(None, entities_dao.insert_ql_add_wechat_result, dm_session_id, customer_id,
                                  self.robot_id,
                                  contact_id, datetime.now(), contact_name, add_way, self.company_id, '')

            # todo 加好友成功回调——2252：改好友备注
            if self.company_id in ['2252', 2252]:
                # 发送打招呼语
                await send_welcome_msg(self.company_id, self.robot_id, contact_id, customer_id)

                # 修改备注
                await send_update_contact_remark(self.company_id, self.robot_id, contact_id, customer_id)
            # todo 加好友成功回调——2242：改好友备注
            if self.company_id in ['2242', 2242]:
                # 修改备注
                await send_update_contact_remark(self.company_id, self.robot_id, contact_id, customer_id)

    @classmethod
    def get_contact_info_by_redis(self, contact_id, type="user"):
        if not contact_id:
            return "", ""
        info = redis_memory.get(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "" + type + ":" + contact_id)
        if info:
            info = json.loads(info)
            name = info.get('name', '')
            avatar = info.get('avatar', '')
            return name, avatar
        return "", ""

    async def process_add_by_phone(self):
        contact_id = self.data.get('contact_uid', '')
        phone = self.data.get('phone', '')
        status = self.data.get('status', '')
        nick_name = self.data.get('name', '')

        if phone and self.company_id in [2252, '2252']:
            robotName = common_util.get_robot_name(redis_memory=redis_memory, company_id=self.company_id,
                                                   robot_id=self.robot_id)

            content_dict = {"加好友通知": "✅申请发送成功\n客服企微：【{}】\n微信手机号：【{}】\n微信昵称：【{}】".format(robotName,
                                                                                        phone,
                                                                                        nick_name)}
            wechat.send_wechat(msg=content_dict, webhook=wework_constants.webhook_url)
            wechat.send_wechat(msg=content_dict, webhook=wework_constants.webhook_url_guoan)

        loops.run_in_executor(None, entities_dao.update_ql_add_wechat_record, phone, status, '', nick_name,
                              contact_id)

    async def process_update_contact_remark(self):
        # todo -修改好友备注回调
        try:
            contact_id = self.data.get('contact_id', '')
            mark_id_list = self.data.get('mark_id_list', '')
            customer_id = ""
            if mark_id_list:
                dm_session_id = mark_id_list[0]
                idArr = str(dm_session_id).split(',')
                if len(idArr) > 1:
                    customer_id = idArr[1]
            # await send_update_contact_remark(self.company_id, self.robot_id, contact_id, customer_id)
        except Exception as ee:
            logger.error('修改好友备注失败：{},{}'.format(self.data, traceback.format_exc()))


async def send_welcome_msg(company_id, robot_id, contact_uid, customer_id, msg_type=2):
    """给用户发送消息"""
    response_json = {}
    token = ""
    if company_id:
        token = await token_manager.get_access_token_by_company_id(company_id)
    req_id = str(uuid.uuid4()).replace("-", "")
    try:
        userInfo = None
        familyName = ''
        if customer_id:
            userInfo = common_util.search_user_by_customerId(company_id, customer_id)
            if userInfo:
                familyName = str(userInfo.get('fullName', ''))[0:1]

        msg = '{}{}'.format(familyName, wework_constants.welcome_msg_2252)

        # 处理params
        payload = {
            "robot_id": robot_id,
            "uniq_sn": req_id,
            "msg": {
                "sender_id": robot_id,
                "receiver_id": contact_uid,
                "msg_id": str(uuid.uuid4()).replace("-", ""),
                "msg_type": msg_type,
                "msg_content": {
                    "text": {
                        "content": msg,
                    }
                }
            }
        }
        headers = {'Content-Type': 'application/json', 'Token': token}
        async with aiohttp.ClientSession() as session:
            async with session.post(wework_constants.WEWORK_INTERFACE_SEND_USER_MSG, json=payload,
                                    headers=headers) as response:
                data = await response.json()
                if response.status == 200 and data.get("errcode") == 0:
                    redis_memory.set(wework_constants.QW_PLANNER_REDIS_KEY_PREFIX + "send_msg_req:" + req_id,
                                     json.dumps({"msg": msg, "receiver_id": contact_uid, "msg_type": msg_type},
                                                ensure_ascii=False),
                                     ex=24 * 3600)
                    response_json['message'] = "请求发送成功"
                else:
                    response_json['message'] = data.get("err_msg")
    except Exception:
        logger.error(traceback.format_exc())
        response_json['message'] = "请求异常"
    return response_json


async def send_update_contact_remark(company_id, robot_id, contact_uid, customer_id):
    """给用户发送消息"""
    response_json = {}
    token = ""
    if company_id:
        token = await token_manager.get_access_token_by_company_id(company_id)
    req_id = str(uuid.uuid4()).replace("-", "")
    try:
        # 处理params
        payload = {
            "robot_id": robot_id,
            "contact_id": contact_uid,
            "remark": customer_id,
            "uniq_sn": str(uuid.uuid4()).replace("-", "")
        }
        headers = {'Content-Type': 'application/json', 'Token': token}
        async with aiohttp.ClientSession() as session:
            async with session.post(wework_constants.WEWORK_INTERFACE_UPDATE_CONTACT_REMARK, json=payload,
                                    headers=headers) as response:
                data = await response.json()
                if response.status == 200 and data.get("errcode") == 0:
                    response_json['message'] = "请求发送成功"
                else:
                    response_json['message'] = data.get("err_msg")
    except Exception:
        logger.error(traceback.format_exc())
        response_json['message'] = "请求异常"
    return response_json


if __name__ == '__main__':
    # content_dict = {"加好友通知": "✅申请发送成功\n客服企微：【{}】\n微信手机号：【{}】\n微信昵称：【{}】".format('陈双', '18501039421', '兔子🐰')}

    content_dict = {
        "加好友通知": "❌申请发送失败\n客服企微：【{}】\n微信手机号：【{}】\n失败原因：【{}】".format('陈双', '18501039421', '540000:没有查找到用户')}
    wechat.send_wechat(msg=content_dict, webhook=wework_constants.webhook_url_guoan)
